<template>
  <view class="work-container">
    <view class="header" :style="{ 'padding-top': `${statusH}px` }">
      <view class="appbar">
        <text>工作台</text>
        <view class="action">
          <image class="icon-style" src="/static/images/work/sys.png" mode="aspectFill" @click="scanCode()" />
        </view>
      </view>
    </view>
    <view class="menu-container">
      <view class="slider-menu">
        <scroll-view scroll-y class="scroll-view-y">
          <view
            v-for="item in menus"
            :key="item.menuId"
            :class="{ active: item.menuId === currentSliderId }"
            class="slider-item"
            @click="currentSliderId = item.menuId"
            >{{ item.menuName }}</view
          >
        </scroll-view>
      </view>
      <view class="child-menu">
        <scroll-view scroll-y class="scroll-view-y">
          <view
            v-for="item in childMenu"
            :key="item.menuId"
            @click="goPage(item.routerPath, item)"
            class="child-menu-item"
          >
            <view>
              <view class="label">{{ item.menuName }}</view>
              <view v-if="getMessageNumByPath(item.routerPath)" class="tip-text">
                {{ getMessageNumByPath(item.routerPath) }}条未处理任务
              </view>
            </view>
            <image class="icon-work-link" src="/static/images/work/icon-work-link.png" />
          </view>
          <view class="h-40"></view>
        </scroll-view>
      </view>
    </view>
    <exam-start-dialog v-model="dialogVisible" :count-tip="countTip" @confirm="startTest" :type="'primary'" />
  </view>
</template>

<script>
import { getTodoData, getInspectMsg, reqGetEduTodoCount, getDeviceTaskMsg } from '@/api/message/index.js'
import { getAppMenu } from '@/api/system/app.js'
import { staticUrl } from '@/config.js'
import store from '@/store'
import { getAlarmInfoMsg } from '@/api/alarm-info'
import { reqCreateExam, reqUserExamCount } from '@/api/educational-training/online-examination'
import ExamStartDialog from '@/pages/work/online-examination/components/ExamStartDialog.vue'
import CuDropdown from '@/components/cu-dropdown/index.vue'
import CuDropdownItem from '@/components/cu-dropdown/cu-dropdown-item.vue'
import { closeNFC, initNFC, readNFC } from '@/utils/nfc'

// 临时根据url处理一下，后面需要在基础服务平台给每个菜单加个唯一标识的key，用来给messageNum做识别
const menuKeysWithMessageKeyMap = {
  '/pages/work/controlCheck/list': 'checkPlanTaskTodoCount', //管控排查
  '/pages/work/hiddenDangerCheck/list': 'dangerPlanTaskTodoCount', //隐患排查
  '/pages/work/hiddenDangerDeal/list': 'dangerManagerTodoCount', //隐患处理
  '/pages/work/training-tasks/index': 'trainingCount', // 培训任务
  '/pages/work/online-examination/index': 'examCount', // 在线考试
  // '/pages/work/training-research/index': 'pxdy', // 培训调研
  '/pages/work/inspectTask/index': 'inspectionSubTaskMyTodoCount', // 巡检任务
  '/pages/work/intelligentPatrolInspection/spotCheck/index': 'spotMyTodoCount', // 点检事项
  '/pages/work/intelligentPatrolInspection/maintenanceMatter/index': 'maintainMyTodoCount', // 维护事项
  '/pages/work/intelligentPatrolInspection/lubricationMatter/index': 'lubricationMyTodoCount', // 润滑事项
  '/pages/work/intelligentPatrolInspection/maintenanceRequirement/index': 'deviceExamineMyTodoCount',
  '/pages/work/training-research/index': 'trainingResearchCount', // 培训调研
  '/pages/work/add-load-operation/list': 'dockWorkCount',

  '/pages/work/alarm-info/list': 'alarmInfoCount', // 报警信息
  '/pages/work/visitor-regist/list': 'visitorRegist' // 访客登记
}
export default {
  data() {
    return {
      indicatorDots: false,
      autoplay: true,
      interval: 3000,
      duration: 1000,
      staticUrl,
      messageNum: {},
      menus: [],
      currentSliderId: 0,
      planId: '',
      countTip: '',
      dialogVisible: false,
      statusH: ''
    }
  },
  components: {
    ExamStartDialog,
    CuDropdown,
    CuDropdownItem
  },
  onLoad() {
    uni.getSystemInfo({
      success: (res) => {
        const { statusBarHeight } = res
        this.statusH = statusBarHeight
      }
    })
  },
  onUnload() {
    closeNFC()
  },
  onShow() {
    if (process.env.NODE_ENV !== 'development') {
      // this.$store.dispatch("GetUpgradeInfo");
    }
    this.getAllNum()
    this.getMenu()
  },
  onPullDownRefresh() {
    this.getAllNum()
    this.getMenu()
  },
  methods: {
    // 开始考试
    async startTest() {
      reqCreateExam(this.planId).then(async ({ data }) => {
        uni.navigateTo({
          url: `/pages/work/online-examination/take-part-online-examination?examPlanId=${data}&start=true`
        })
      })
    },
    // 获取所有消息数量
    getAllNum() {
      getTodoData().then(({ data }) => {
        this.setMessageNum(data)
      })
      getInspectMsg().then(({ data }) => {
        this.setMessageNum(data)
      })
      reqGetEduTodoCount().then(({ data }) => {
        this.setMessageNum({
          trainingCount: data.trainCount || 0,
          examCount: data.examCount || 0
        })
      })
      getDeviceTaskMsg().then(({ data }) => {
        this.setMessageNum({
          spotMyTodoCount: data.spotMyTodoCount,
          lubricationMyTodoCount: data.lubricationMyTodoCount,
          maintainMyTodoCount: data.maintainMyTodoCount
        })
      })
      getAlarmInfoMsg().then(({ data }) => {
        this.setMessageNum({
          alarmInfoCount: data?.count
        })
      })
    },
    setMessageNum(data) {
      uni.stopPullDownRefresh()
      this.messageNum = {
        ...this.messageNum,
        ...data
      }
    },
    getMenu() {
      getAppMenu().then(({ data }) => {
        if (data.length) {
          this.menus = data[0].children
          if (!this.currentSliderId) {
            this.currentSliderId = this.menus[0].menuId
          }
        }
      })
    },
    goPage(url, item) {
      if (url === '/pages/work/controlCheck/list') {
        if (!store.getters.imeiCode) {
          this.$modal.msg('您还未录入IMEI识别码，请先完成录入，否则将无法进行管控排查。')
          setTimeout(function () {
            uni.switchTab({
              url: '/pages/mine/index'
            })
          }, 1500)
          return
        }
      }
      if (item.asFrame === '1') {
        uni.navigateTo({
          url,
          success: function (res) {
            // 通过eventChannel向被打开页面传送数据
            res.eventChannel.emit('app:menu', item.children)
          }
        })
      } else if (item.asFrame === '0') {
        const path = encodeURIComponent(item.routerPath)
        uni.navigateTo({
          url: `/pages/work/report-form/query/view?title=${item.menuName}&url=${path}`
        })
      }
    },
    goHiddenDangerCheck() {
      uni.navigateTo({
        url: '/pages/work/hiddenDangerCheck/list'
      })
    },
    goHiddenDangerReport() {
      uni.navigateTo({
        url: '/pages/work/hiddenDangerReport/index'
      })
    },
    goHiddenDangerDeal() {
      uni.navigateTo({
        url: '/pages/work/hiddenDangerDeal/list'
      })
    },
    goControlCheck() {
      uni.navigateTo({
        url: '/pages/work/controlCheck/list'
      })
    },
    goHiddenDangerBook() {
      uni.navigateTo({
        url: '/pages/work/hiddenDangerBook/list'
      })
    },
    changeGrid(e) {
      this.$modal.showToast('模块建设中~')
    },
    nfcDeal() {
      if (!initNFC()) return
      if (this.timeout) {
        clearTimeout(this.timeout)
        this.timeout = null
      }
      this.timeout = setTimeout(function () {
        closeNFC()
      }, 5000)

      readNFC((devicePositionNum) => {
        console.log('read devicePositionNum', devicePositionNum)
        if (this.timeout) {
          clearTimeout(this.timeout)
          this.timeout = null
        }
        uni.navigateTo({
          url: `/pages/work/device-manage/detail?devicePositionNum=${devicePositionNum}`
        })
      })
    },
    scanCode() {
      let that = this
      uni.scanCode({
        scanType: ['qrCode'],
        success: function (res) {
          console.log('scanCode', res)
          if (res.scanType !== 'QR_CODE') {
            uni.navigateTo({
              url: '/pages/work/training-tasks/sign-error'
            })
          } else if (!res.result.startsWith('/qinghai')) {
            /*uni.navigateTo({
								url: '/pages/work/training-tasks/sign-error',
							});*/
            uni.navigateTo({
              url: `/pages/work/position-label/detail?code=${res.result}`
            })
          } else {
            let path = res.result.split('/qinghai')[1]
            if (path.indexOf('online-examination/take-part-online-examination') > -1) {
              // app端扫码考试
              that.planId = path.split('?planId=')[1]
              reqUserExamCount(that.planId).then((res) => {
                that.countTip = `${res.data.maxExamCount - 1}`
                that.dialogVisible = true
              })
            } else {
              let path = res.result.split('/qinghai')[1]
              console.log(`/pages/work${path}`)
              uni.navigateTo({
                url: `/pages/work${path}`
              })
            }
          }
        }
      })
    }
  },
  computed: {
    childMenu() {
      if (!this.currentSliderId) {
        return []
      }
      const arr = this.menus.filter((pet) => pet.menuId === this.currentSliderId)
      if (arr.length) {
        return arr[0].children
      } else {
        return []
      }
    },
    getMessageNumByPath() {
      return function (path) {
        const key = menuKeysWithMessageKeyMap[path]
        if (!key || !this.messageNum || !Object.keys(this.messageNum).length) return 0

        const messageNum = this.messageNum[key]
        return messageNum > 99 ? '99+' : messageNum
      }
    }
  }
}
</script>

<style lang="scss">
$header-height: 230rpx;
.work-container {
  background: #fff;
  .header {
    height: $header-height;
    background: url('@/static/images/work/bg-work.png') no-repeat center;
    background-size: cover;
    text-align: center;
    position: relative;
    .appbar {
      position: relative;
      .action {
        position: absolute;
        right: 0;
        top: 0;
        display: flex;
        align-items: center;
      }
      .icon-style {
        width: 40rpx;
        height: 40rpx;
        margin-right: 20rpx;
      }
    }
    text {
      color: #fff;
      font-weight: 500;
      font-size: 36rpx;
      text-align: center;
    }
  }

  .menu-container {
    display: flex;
    height: calc(100vh - $header-height);
  }
  .slider-menu {
    width: 210rpx;
    background: #f8f8fb;
    flex-shrink: 0;
    .slider-item {
      height: 150rpx;
      position: relative;
      display: flex;
      align-items: center;
      padding-left: 30rpx;
      justify-content: start;
      font-weight: 400;
      font-size: 30rpx;
      color: #666666;
      &.active {
        background: #fff;
      }
      &.active::after {
        content: '';
        background: #2ac0c8;
        position: absolute;
        left: 1px;
        top: 50%;
        height: 30rpx;
        width: 6rpx;
        transform: translateY(-15rpx);
      }
    }
  }
  .child-menu {
    flex: 1;
    padding: 0 40rpx;
    .scroll-view-y {
      height: calc(100vh - $header-height);
    }
    .child-menu-item {
      height: 156rpx;
      background: url('@/static/images/work/bg-work-menu.png') center no-repeat;
      background-size: 100% 156rpx;
      margin-top: 40rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 40rpx;
      .label {
        font-weight: 500;
        font-size: 32rpx;
        color: #185b5e;
      }
      .icon-work-link {
        width: 40rpx;
        height: 40rpx;
      }
      .tip-text {
        font-weight: 400;
        font-size: 26rpx;
        color: #ff561e;
      }
    }
  }
}
</style>
